<?php
// +----------------------------------------------------------------------
// | 用户收藏服务
// +----------------------------------------------------------------------
// | 主要服务于User Favorites数据处理
// +----------------------------------------------------------------------
// | 错误编码头 249xxx
// +----------------------------------------------------------------------

namespace common\service;

use common\model\UserFavoritesModel;
use support\SingletonTrait;

class UserFavoritesService
{
    // 单例工具
    use SingletonTrait;
    private $userFavoritesModel;
    public function __construct() {
        $this->userFavoritesModel =  model(UserFavoritesModel::class);
    }


	/**
	 * 获取用户收藏信息
	 * @param $param
	 * @param $userId
	 *
	 * @return array|mixed|string
	 */
    public function getUserFavorites($param ,$userId)
    {
		if(empty($param) || empty($userId)){
			return [];
		}
		$filter = $param['filter'] ?? [];
		$page = $param['page'] ?? [0, 20];
		$userId = $filter['user_id'] ?? $userId;
        // 获取用户收藏参数
		$result =  $this->userFavoritesModel
            ->field(['id','user_id','collection_id','link_type'])
            ->where(['user_id' => $userId ,'link_type' => $filter['link_type']])
			->page($page[0], $page[1])
			->order('id desc,create_time desc')
            ->select();
        if(empty($result)){
            return [];
        }
		return $result;
    }



    /**
     * 新增收藏信息
     * @param $param
     * @param $userId
     *
     * @return array|bool|int|string
     */
	public function createUserFavorites($param, $userId)
	{
		if (empty($param)) {
			return [];
		}
		//查年收藏信息是否存在,如果不存在创建收藏,存在直接返回信息
        $where =[
            'collection_id' => ['in', $param['id']],
            'link_type' => $param['link_type'],
            'user_id' => $userId
        ];
		$result = $this->userFavoritesModel
            ->field(['collection_id'])
            ->where($where)
            ->select();

        $ids = array_column($result, 'collection_id');
        $diffIds = array_diff($param['id'],$ids);
		$data = [];
        $time = time();
        foreach ($diffIds as $item){
            $data[] = [
                'user_id' => $userId,
                'link_type' =>$param['link_type'],
                'collection_id' => $item,
                'create_time' => $time,
                'update_time' => $time
            ];
        }
        return $this->userFavoritesModel->addAll($data);
	}

    /**
     * 删除收藏
     * @param $param
     * @param $userId
     *
     * @return array|void
     */
    public function deleteUserFavorites($param, $userId)
    {
        if (empty($param)) {
            return [];
        }

        $where = [
            'collection_id' => ['in', $param['id']],
            'user_id' => $userId,
            'link_type' => $param['link_type']
        ];
        return $this->userFavoritesModel->where($where)->delete();
    }
}
